﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MShop.Core.DataAccess;
using MShop.Core.Domain;

namespace MShop.Web.Areas.Admin.Controllers
{
    public class AdController : SecureController
    {
        
        private readonly ICommonDao<Ad> _CommonDao;
        public AdController(ICommonDao<Ad> commonDao)
        {
            _CommonDao = commonDao;          
        }

        public ActionResult Index()
        {
            return View(_CommonDao.GetAll());
        }
        public ActionResult Create()
        {
            var ad = new Ad();
            ad.Sort = _CommonDao.GetAll().Count() + 1;
            return View(ad);
        }

        [HttpPost]
        public ActionResult Create(Ad ad)
        {

            if (ModelState.IsValid)
            {
                _CommonDao.Save(ad);
                _CommonDao.SaveChanges();
                return RedirectToAction("index");
            }
            return View(ad);
        }

        public ActionResult Edit(int id)
        {

            return View(_CommonDao.GetById(id));
        }


        public ActionResult Delete(int id)
        {
            var ad = _CommonDao.GetById(id);
            _CommonDao.Delete(ad);
            _CommonDao.SaveChanges();
            return RedirectToAction("index");
        }


        [HttpPost]
        public ActionResult Edit(int id, Ad ad)
        {
            if (ModelState.IsValid)
            {
                var dbad = _CommonDao.GetById(id);
                UpdateModel<Ad>(dbad, new string[] { "Title", "ImageUrl", "Sort", "RedirectUrl", "Status" });
                _CommonDao.SaveChanges();
                return RedirectToAction("index");
            }
            return View(ad);


        }
    }
}
